const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const InitManager = require('./bin/init')
InitManager.initCore(app)
// const welcome = new require('koa-router')(); // 创建路由，支持传递参数
// const fs = require('fs')
// welcome.get('/', (ctx) => {
//   ctx.set('Content-Type', "text/html;charset=utf-8");
//   ctx.body = fs.createReadStream('./doc/api.html')
// })
// welcome.get('/db', (ctx) => {
//   ctx.set('Content-Type', "text/html;charset=utf-8");
//   ctx.body = fs.createReadStream('./doc/db.html')
// })
// welcome.get('/postman', (ctx) => {
//   ctx.set('Content-Type', "application/json;charset=utf-8");
//   ctx.body = fs.createReadStream('./doc/postman.json')
// })
// app.use(welcome.routes())
app.use(require('koa-static')(__dirname + '/views/dist'))
//跨域处理
const cors = require('./app/middlewares/cors')
app.use(cors)
// 检测token
const auth = require('./app/middlewares/auth')
app.use(auth)
const api = require('./app/api/v1/index')
const adminApi = require('./app/api/v1/admin')
// error handler
onerror(app)
// 解析
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
// ctx.url
app.use(logger())
// logger
app.use(require('./app/middlewares/logger'))
// routes
app.use(api.routes(), api.allowedMethods())
app.use(adminApi.routes(), adminApi.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})
module.exports = app
